package com.zhl.configurer;

import com.zhl.entity.Role;
import com.zhl.entity.User;
import com.zhl.service_.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Author zhl
 * @Description
 * @Date
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //给当前用户授权的权限（功能权限、角色）
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        User user = (User) principals.getPrimaryPrincipal();

        //授权,角色权限从数据库获取
        user = userService.queryUserByid(user.getId());
        List<Role> roles = user.getRoles();
        for (Role role:roles) {
//            System.out.println("用户:权限"+user.getUsername()+":"+role.getName());
            authorizationInfo.addRole(role.getName());
        }

        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal();
        String password = (String) token.getPrincipal();
        //开发中，这里都是去数据库查询
        User user = userService.login(username, password);
        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }

        if (user.getAvailable()!=1){
            throw  new LockedAccountException("账户已被锁定");
        }
        //自动比对查到的密码和提交的密码,不一致就会抛异常IncorrectCredentialsException
        return  new SimpleAuthenticationInfo(user, user.getPassword(),getName());
    }

}